package com.eroad.product.tools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.login.LoginActivity;
import com.emm.yixun.mobile.model.Logout;
import com.example.xf.MainActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.HashMap;
import java.util.Map;

import xf.tointinataface.FlyprintInataface;
import xf.tools.Loading;

/**
 * 提示框，主要针对退出时使用
 */
public class PopuContent {

    private static final String TAG = "PopuContent";

    public static View view3;
    public static PopupWindow popu_call;

    public static Activity a;

    private static SystemBarTintManager tintManager;

    /**
     * 设置顶部title背景颜色 此处设置值为：透明
     */
    public static void SetTopTitleBgColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            tintManager = new SystemBarTintManager(a);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(color);// 通知栏所需颜色
        }
    }

    private static void setTranslucentStatus(boolean on) {
        Window win = a.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public static void poPu(final Activity activity, String msg, boolean isVsCancel, final int type) {
        poPu(activity, msg, isVsCancel, type, null);
    }

    public static void show(Activity activity, String msg, Result result) {
        poPu(activity, msg, true, 999, result);
    }

    public static void show(Activity activity, String msg, int code, Result result) {
        poPu(activity, msg, false, code, result);
    }

    /**
     * <p>
     * <b>Title：</b> 公用弹出框
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param activity   当前activity
     * @param msg        内容
     * @param isVsCancel 是否显示取消按钮
     * @param type       99为退出，不为99为普通模式 77 为异地登录
     * @author tangxin
     * @date 2016年12月15日 下午2:07:53
     */
    @SuppressLint("WrongConstant")
    public static void poPu(final Activity activity, String msg, boolean isVsCancel, final int type, final Result result) {
        if (null != popu_call) {
            popu_call.dismiss();
        }
        a = activity;
        view3 = LayoutInflater.from(activity).inflate(R.layout.popu_shuerdp, null);
        popu_call = new PopupWindow(view3, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        popu_call.setFocusable(true);

        SetTopTitleBgColor(R.color.status_view);

        popu_call.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popu_call.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        popu_call.showAtLocation(view3, Gravity.CENTER, 0, 0);
        popu_call.showAsDropDown(view3, 0, 0);
        popu_call.setFocusable(true);
        popu_call.setOutsideTouchable(true);
        view3.setFocusable(true);
        view3.setFocusableInTouchMode(true);

        view3.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && null != result && type != -1) {
                    popu_call.dismiss();
                }
                return false;
            }
        });
        view3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != result && type != -1) {
                    popu_call.dismiss();
                }
            }
        });

        // 取消
        TextView dismiss = (TextView) view3.findViewById(R.id.dismiss);
        // 确定
        TextView btSave = (TextView) view3.findViewById(R.id.shuerbtn);

        if (type == 999) {
            btSave.setText("完善客户信息");
        }

        TextView ts_message = (TextView) view3.findViewById(R.id.ts_message);
        ts_message.setText(msg);
        if (isVsCancel) {
            dismiss.setVisibility(View.VISIBLE);
        } else {
            dismiss.setVisibility(View.GONE);
        }
        dismiss.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                tintManager.setStatusBarTintResource(R.color.transparent);// 通知栏所需颜色
                popu_call.dismiss();
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                lp.alpha = 1f;
                activity.getWindow().setAttributes(lp);
            }
        });
        btSave.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                tintManager.setStatusBarTintResource(R.color.transparent);// 通知栏所需颜色
                popu_call.dismiss();
                EmmApplication.setLog(activity);
                if (null != result) {
                    result.result();
                    return;
                }
                if (type == 99) {// 退出
                    logout();
                } else if (type == 77) {
                    EmmApplication.setIsLogin("2");// 存储是否已登录标识
                    EmmApplication.count++;
                    EmmApplication.context.sendBroadcast(new Intent("OpenLogin_Besa"));
                } else if (type == 55) {// 到首页
                    // 首页存在就关闭，不存在就不做操作
                    FlyprintInataface.finishMain();
                    // 重新打开首页，加载数据
                    Intent intent = new Intent(BaseActivity.activity, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    BaseActivity.activity.startActivity(intent);
                    BaseActivity.activity.finish();
                } else if (type == 66) {
                    FlyprintInataface.mLoginClick.onLogin(1);// 选中首页
                    FlyprintInataface.mLoginClick.ReloadProjectList();// 刷新数据
                } else if (type == 44) {
                    FlyprintInataface.mLoginClick.ReloadProjectList();// 刷新数据
                } else if (type == 33) {
                    FlyprintInataface.mLoginClick.ReloadProjectList();// 刷新数据
                }
            }
        });
    }

    public static void poPuHind() {
        try {
            popu_call.dismiss();
        } catch (NullPointerException e) {
        }
    }

    static Logout logout;

    public static void logout() {
        EmmApplication.updateUrl("logout");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getMemberInfo-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);

                EmmApplication.setIsLogin("2");
                EmmApplication.setIsLoginToken("");
                EmmApplication.setIsLoginUserId("");// 重置登陆信息

                Intent intent = new Intent();
                intent.putExtra("GO", "2");
                intent.setClass(a, LoginActivity.class);
                a.startActivity(intent);

                a.sendBroadcast(new Intent(EmmApplication.logout));// 广播通知
                a.finish();

            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(a, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);

                // EmmApplication.T("退出成功");

                EmmApplication.setIsLogin("2");
                EmmApplication.setIsLoginToken("");
                EmmApplication.setIsLoginUserId("");// 重置登陆信息

                Intent intent = new Intent();
                intent.putExtra("GO", "2");
                intent.setClass(a, LoginActivity.class);
                a.startActivity(intent);

                a.sendBroadcast(new Intent(EmmApplication.logout));// 广播通知
                a.finish();

                if (content == null) {
                    return;
                }

                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                logout = JSONObject.parseObject(resData.toString(), Logout.class);

                if ("1".equals(logout.getResult())) {
                    Log.v("获取成功", "");

                } else {
                    Log.v("获取失败", "errorCode:" + logout.getErrorCode().toString() + "errorMsg:"
                            + logout.getErrorMsg().toString());
                }
            }
        });
    }

}
